import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import OneWayFlightSearch from "@/components/OneWayFlightSearch.vue";
import RoundTripFlightSearch from "@/components/RoundTripFlightSearch.vue";
import AttractionList from "@/views/AttractionList.vue";

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/auth/Login.vue'),
        meta: {
            title: '登录',
            requiresAuth: false,
            hideInMenu: true
        }
    },
    {
        path: '/',
        redirect: '/search'
    },
    {
        path: '/search',
        name: 'MainFlightSearch',
        component: () => import('@/views/MainFlightSearch.vue'),
        meta: {
            title: '机票搜索',
            icon: 'Search',
            requiresAuth: true // 需要登录
        }
    },
    {
        path: '/flights/oneway',
        name: 'OneWaySearch',
        component: OneWayFlightSearch,
        meta: {
            title: '单程航班搜索',
            requiresAuth: true // 改为需要登录
        }
    },
    {
        path: '/flights/roundtrip',
        name: 'RoundTripSearch',
        component: RoundTripFlightSearch,
        meta: {
            title: '往返航班搜索',
            requiresAuth: true // 改为需要登录
        }
    },
    {
        path: '/hotel-search',
        name: 'HotelSearch',
        component: () => import('@/views/HotelSearch.vue'),
        meta: {
            title: '酒店搜索',
            icon: 'Search',
            requiresAuth: true
        }
    },
    {
        path: '/attractions',
        name: 'AttractionList',
        component: AttractionList,
        meta: {
            title: '景点管理',
            requiresAuth: true
        }
    },
    {
        path: '/product-management',
        name: 'ProductManagement',
        component: () => import('@/views/product/ProductManagement.vue'),
        meta: {
            title: '商品路线管理',
            icon: 'ShoppingBag',
            requiresAuth: true
        }
    },
    {
        path: '/products',
        redirect: '/product-management?tab=products'
    },
    {
        path: '/products/:id',
        name: 'ProductDetail',
        component: () => import('@/views/product/ProductDetail.vue'),
        props: true,
        meta: {
            title: '商品详情',
            requiresAuth: true
        }
    },
    {
        path: '/rules',
        redirect: '/product-management?tab=rules'
    },
    {
        path: '/capital',
        redirect: '/product-management?tab=attractions'
    },
    {
        path: '/custom-content',
        name: 'CustomContent',
        component: () => import('@/views/product/CustomContentManagement.vue'),
        meta: {
            title: '自定义行程内容管理',
            requiresAuth: true
        }
    },
    {
        path: '/products/:id/edit',
        name: 'ProductEdit',
        component: () => import('@/views/product/PageDivEditor.vue'),
        meta: {
            title: '编辑商品内容',
            requiresAuth: false
        }
    },
    {
        path: '/tasks',
        name: 'TaskManagement',
        component: () => import('@/views/ScheduleTaskManager.vue'),
        meta: {
            title: '定时任务管理',
            icon: 'Timer',
            requiresAuth: true
        }
    },
    {
        path: '/settings',
        name: 'SystemSettings',
        component: () => import('@/views/SystemSettings.vue'),
        meta: {
            title: '系统设置',
            icon: 'Setting',
            requiresAuth: true
        }
    },
    {
        path: '/404',
        name: 'NotFound',
        component: () => import('@/views/404.vue'),
        meta: {
            title: '页面未找到',
            requiresAuth: false
        }
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: '/404'
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { top: 0 }
        }
    }
})

// 白名单路由（不需要登录验证的路由）
const whiteList = ['/login', '/404']

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()

    // 初始化用户状态
    if (!userStore.token) {
        userStore.initUserState()
    }

    // 设置页面标题
    if (to.meta.title) {
        document.title = `${to.meta.title} - 搜索系统`
    }

    // 如果已经登录，访问登录页面则重定向到首页
    if (userStore.isLoggedIn && to.path === '/login') {
        next('/')
        return
    }

    // 检查是否需要登录验证
    if (to.meta.requiresAuth !== false && !whiteList.includes(to.path)) {
        if (!userStore.isLoggedIn) {
            // 未登录，重定向到登录页
            ElMessage.warning('请先登录')
            next({
                path: '/login',
                query: { redirect: to.fullPath } // 保存重定向路径
            })
            return
        }

        // 已登录但用户信息为空，尝试获取用户信息
        if (!userStore.userInfo) {
            try {
                await userStore.getUserInfo()
            } catch (error) {
                // 获取用户信息失败，可能token已过期
                console.error('获取用户信息失败:', error)
                next({
                    path: '/login',
                    query: { redirect: to.fullPath }
                })
                return
            }
        }
    }

    next()
})

// 全局后置钩子
router.afterEach((to) => {
    // 可以在这里做一些页面访问统计等
    console.log('导航到:', to.path)
})

export default router